package com.yourenbang.lingyun.transaction.web.service.impl;

import com.yourenbang.lingyun.core.util.redis.CacheKey;
import com.yourenbang.lingyun.core.util.redis.RedisUtils;
import com.yourenbang.lingyun.transaction.web.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

@Slf4j
@Service()
public class  CommonServiceImpl implements CommonService {

    @Autowired
    private RedisUtils redis;
    @Autowired
    private Environment env;

    /**
     * 校验多次提交
     * @param key 唯一标识,一般为 （userId + : + 方法名）
     * @return true:重复提交
     */
    @Override
    public boolean repeatSubmit(String key) {
        return repeatSubmit(key, 3);
    }

    /**
     * 校验多次提交
     * @param key    唯一标识,一般为 （userId + : + 方法名）
     * @param second 秒数
     * @return true:重复提交
     */
    @Override
    public boolean repeatSubmit(String key, int second) {
        if(StringUtils.isBlank(key)){
            return false;
        }
        CacheKey cacheKey = new CacheKey(CacheKey.CacheKeyPrefix2.pay, StringUtils.join("repeatSubmit:", key));
        return !redis.setIfAbsent(cacheKey, "repeatSubmit", second);
    }

    private boolean isSpecifiedEnvironment(String environment){
        String[] profiles = env.getActiveProfiles();
        for(String actice : profiles){
            if(StringUtils.contains(actice, environment)){
                return true;
            }
        }
        return false;

    }

    /**
     * 判断当前是否为生产环境
     */
    @Override
    public boolean isProd() {
        boolean flag = isSpecifiedEnvironment("prod");
        log.debug("是否生产环境:{}", flag);
        return flag;
    }
}
